const mongoose = require('mongoose');

const planSchema = new mongoose.Schema({
  cadreId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Cadre',
    required: [true, '授课干部为必填项']
  },
  universityId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'University',
    required: [true, '授课高校为必填项']
  },
  courseSeries: {
    type: String,
    enum: ['领导力与战略管理', '公共政策与治理', '经济发展与改革', '社会建设与民生', '文化建设与传承', '生态文明建设', '国防与安全', '外交与国际关系', '党建与廉政', '其他']
  },
  courseName: {
    type: String,
    required: [true, '课程名称为必填项'],
    trim: true
  },
  classDate: {
    type: Date,
    required: [true, '上课日期为必填项']
  },
  classTime: {
    type: String,
    required: [true, '上课时间为必填项'],
    trim: true
  },
  location: {
    type: String,
    required: [true, '授课地点为必填项'],
    trim: true
  },
  plannedHours: {
    type: Number,
    required: [true, '计划学时为必填项'],
    min: [0.5, '计划学时不能少于0.5小时'],
    max: [8, '计划学时不能超过8小时']
  },
  teachingStatus: {
    type: String,
    required: [true, '授课状态为必填项'],
    enum: ['计划中', '进行中', '已完成', '已取消', '已调整'],
    default: '计划中'
  },
  teachingSemester: {
    type: String,
    required: [true, '授课学期为必填项'],
    trim: true
  },
  remarks: {
    type: String,
    trim: true
  }
}, {
  timestamps: true,
  toJSON: { virtuals: true },
  toObject: { virtuals: true }
});

// 复合索引：确保同一干部在同一时间不能有多个授课安排
planSchema.index({ cadreId: 1, classDate: 1, classTime: 1 }, { unique: true });

// 其他索引
planSchema.index({ universityId: 1 });
planSchema.index({ teachingStatus: 1 });
planSchema.index({ teachingSemester: 1 });
planSchema.index({ classDate: 1 });

// 虚拟字段：是否为本周授课
planSchema.virtual('isThisWeek').get(function() {
  if (!this.classDate) return false;
  
  const now = new Date();
  const startOfWeek = new Date(now);
  startOfWeek.setDate(now.getDate() - now.getDay());
  startOfWeek.setHours(0, 0, 0, 0);
  
  const endOfWeek = new Date(startOfWeek);
  endOfWeek.setDate(startOfWeek.getDate() + 6);
  endOfWeek.setHours(23, 59, 59, 999);
  
  return this.classDate >= startOfWeek && this.classDate <= endOfWeek;
});

module.exports = mongoose.model('Plan', planSchema);
